package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskServiceCallTicketMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskServiceCallTicket;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskServiceCallTicketService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskServiceCallTicketServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskServiceCallTicketMapper, TaskAutotaskServiceCallTicket>
        implements TaskAutotaskServiceCallTicketService {

    @Override
    public void sync(ResultEntity content) {
        log.debug("Auto task ServiceCallTickets receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskServiceCallTicket data = TaskAutotaskServiceCallTicket.builder()
                .serviceCallTicketsId(super.getLongValue(entity.get("id")))
                .serviceCallId(super.getLongValue(entity.get("serviceCallID")))
                .ticketId(super.getLongValue(entity.get("ticketID")))
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());

        TaskAutotaskServiceCallTicket dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskServiceCallTicket>lambdaQuery()
                .eq(TaskAutotaskServiceCallTicket::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskServiceCallTicket::getServiceCallTicketsId, data.getServiceCallTicketsId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }
}
